/* ptpd.c */

#include "ptpd.h"
#include "config_api.h"
#include "manager_task.h"
#include "ptpd.h"
#include "uc_log.h"
#include <rtthread.h>

RunTimeOpts rtOpts; /* statically allocated run-time configuration data */

static void ptpd_thread(void *parameter)
{
    PtpClock *ptpClock;

    /* initialize run-time options to default values */
    rtOpts.announceInterval = DEFAULT_ANNOUNCE_INTERVAL;
    rtOpts.syncInterval = DEFAULT_SYNC_INTERVAL;
    rtOpts.clockQuality.clockAccuracy = DEFAULT_CLOCK_ACCURACY;
    rtOpts.clockQuality.clockClass = DEFAULT_CLOCK_CLASS;
    rtOpts.clockQuality.offsetScaledLogVariance = DEFAULT_CLOCK_VARIANCE;
    rtOpts.priority1 = DEFAULT_PRIORITY1;
    rtOpts.priority2 = DEFAULT_PRIORITY2;
    rtOpts.domainNumber = DEFAULT_DOMAIN_NUMBER;
    rtOpts.slaveOnly = SLAVE_ONLY;
    rtOpts.currentUtcOffset = DEFAULT_UTC_OFFSET;
    rtOpts.noResetClock = DEFAULT_NO_RESET_CLOCK;
    rtOpts.noAdjust = NO_ADJUST;
    rtOpts.inboundLatency.nanoseconds = DEFAULT_INBOUND_LATENCY;
    rtOpts.outboundLatency.nanoseconds = DEFAULT_OUTBOUND_LATENCY;
    rtOpts.s = DEFAULT_DELAY_S;
    rtOpts.ap = DEFAULT_AP;
    rtOpts.ai = DEFAULT_AI;
    rtOpts.max_foreign_records = DEFAULT_MAX_FOREIGN_RECORDS;
    rtOpts.E2E_mode = RT_TRUE;

    // if mode is 0,slave,else master,default slave
    if (UC_1588_DEV_SLAVE == uc_static_get_wiota_ts_cfg()->dev_type)
    {
        rtOpts.slaveOnly = RT_TRUE;
        TRACE_I("IEEE 1588 v2 is Slave mode");
    }
    else
    {
        rtOpts.slaveOnly = RT_FALSE;
        TRACE_I("IEEE 1588 v2 is in Master mode");
    }

    // #ifndef PTPD_DBG
    //     rtOpts.displayStats = RT_TRUE;
    // #endif

    /*Initialize run time options with command line arguments*/
    ptpClock = ptpdStartup(&rtOpts);
    if (RT_NULL == ptpClock)
    {
        return;
    }

    /* do the protocol engine */
    ptpdProtocolRun(&rtOpts, ptpClock);

    ptpdShutdown();

    return;
}

void ptpd_init(void)
{
    rt_thread_t ptpd = RT_NULL;

    if (0 == manager_thread_create((void *)&ptpd, "ptpd", ptpd_thread, RT_NULL, 512, RT_MAIN_THREAD_PRIORITY / 3 + 3, 5))
    {
        TRACE_I("ptpd_init suc");
        rt_thread_startup(ptpd);
    }
    else
    {
        TRACE_I("ptpd_init fail");
    }
}
